import './index.less'
import { useState, useCallback } from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';
import { setStateToken } from '@/store/moudles/loginStore';
import { LoginApi } from "@/apis/login";

interface LoginFormType {
    username: string,
    password: string,
    remember: boolean
}


export default function Login() {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [messageApi, contextHolder] = message.useMessage();
    const [loading, setLoading] = useState(false);

    // 使用 useCallback 保证 onFinish 的引用稳定
    const onFinish = useCallback((values: LoginFormType) => {
        setLoading(true);
        LoginApi(values).then(res => {
            const res_data = res.data;
            if (res_data.code === 200) {
                messageApi.open({
                    type: 'success',
                    content: '登录成功',
                });
                setTimeout(() => {
                    dispatch(setStateToken(res_data.token));
                    navigate('/', { replace: true });
                }, 1000);

            }
        }).finally(() => {
            setLoading(false);
        });
    }, [dispatch]);

    return (
        <div className='login'>
            {contextHolder}
            <Form
                name="normal_login"
                className="login-form"
                size='large'
                initialValues={{ remember: true }}
                onFinish={onFinish}
            >
                <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入你的账号!' }]}
                >
                    <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" />
                </Form.Item>
                <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入你的密码!' }]}
                >
                    <Input
                        prefix={<LockOutlined className="site-form-item-icon" />}
                        type="password"
                        placeholder="密码"
                    />
                </Form.Item>
                <Form.Item>
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                        <Checkbox>记住密码</Checkbox>
                    </Form.Item>
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading} className="login-form-button">
                        {loading ? <span>登 录 中...</span> : <span>登 录</span>}
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}